/**
  ETFAna project, Anyang Normal University && IMP-CAS
  \brief just a general conversion app - for those who do not bother installing
  etfana
  \author SUN Yazhou, asia.rabbit@163.com
  \since 2023-12-24
  \date 2023-12-24 last modified
  \attention
  changelog
  <table>
  <tr>  <th>Date         <th>Author      <th>Description                   </tr>
  <tr>  <td>2023-12-24   <td>Asia Sun    <td>file created                  </tr>
  </table>

  \copyright Copyright (c) 2021-2024 Anyang Normal U. && IMP-CAS with LGPLv3 LICENSE
*/

#include <iostream>
#include "TFile.h"
#include "TTree.h"
#include "ETFVMEEvent.h"
#include "ETFPXISection.h"

using std::cout;
using std::endl;
using std::flush;

int main(int argc, const char *argv[]){
  if(argc < 2){
    cout << "Illegal input. Follow the syntax below:" << endl;
    cout << "./cv <f1_rootfile>" << endl;
  } // end if

  TFile *f = new TFile(argv[1]);
  TTree *etf = (TTree *)f->Get("etf");
  // TTree *et = (TTree *)f->Get("et");
  ETFPXISection *p = new ETFPXISection();
  etf->SetBranchAddress("pxi0", &p);
  TFile *f1 = new TFile("luo.root", "recreate");
  TTree *tout = new TTree("tout", "Output Tree - of much simpler form");
  int bunchId;
  tout->Branch("bunchId", &bunchId, "bunchId/I");

  const int n = etf->GetEntriesFast();
  // const int n = 100;
  // int bunchId0 = -1; // bunchId of the last event
  for(int i = 0 ; i < n; i++){
    etf->GetEntry(i);
    bunchId = p->GetBunchID();
    // if(bunchId < bunchId0) bunchId += 4096;
    // bunchId0 = bunchId;
    tout->Fill();
    cout << "Processing event " << i << "\r" << flush;
  } // end for over events

  f1->cd();
  tout->Write("", TObject::kOverwrite);
  f1->Close();
  cout << "Totally " << n << " events conversioned. \033[32;1m:)\033[0m" << endl;
  cout << "The result has been stored in luo.root" << endl;

  return 0;
} // end main function
